package com.tongxin.van.frameworkcanary.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;

import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tongxin.van.frameworkcanary.R;

import java.io.ByteArrayOutputStream;

/**
 *
 * author: VanyLiu
 * email: 13212674795@163.com
 * description:微信分享工具类
 *
**/

public class WXUtils {
    public static final String APPID = "wxb259d9160d1a80b9";

    /**
     * 分享图片
     *
     * @scene 场景，如下：
     * SendMessageToWX.Req.WXSceneSession 值0（微信好友）
     * SendMessageToWX.Req.WXSceneTimeline 值1（朋友圈）
     */
    public static void shareImage(Context context, int scene, String imagePath) {
        //注册
        IWXAPI msgApi = WXAPIFactory.createWXAPI(context, APPID);
        if (!msgApi.isWXAppInstalled()) {
            ToastUtils.showShort("您还没有安装微信");
            return;
        }
        //创建图片微信分享对象
        WXImageObject imgObj = new WXImageObject();
        imgObj.setImagePath(imagePath);
        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = imgObj;

        //设置缩略图
        Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
        Log.d("WXUtils", "bitmap.getByteCount()" + bitmap.getByteCount());
        Bitmap thumbBmp = Bitmap.createScaledBitmap(bitmap, 40, 40, true);
        bitmap.recycle();
        Log.d("WXUtils", "thumbBmp.getByteCount()" + thumbBmp.getByteCount());
        msg.thumbData = bmpToByteArray(thumbBmp, false);  // 设置缩略图

        //启动分享
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = "img" + System.currentTimeMillis();
        req.message = msg;
        req.scene = scene;
        msgApi.sendReq(req);
    }


    /**
     * 分享网页
     *
     * @scene 场景，如下：
     * SendMessageToWX.Req.WXSceneSession 值0（微信好友）
     * SendMessageToWX.Req.WXSceneTimeline 值1（朋友圈）
     */
    public static void shareWebPage(final Context context, final String title, final String description, final String imageUrl, final String webUrl, final int scene) {
        //注册微信Key
        final IWXAPI msgApi = WXAPIFactory.createWXAPI(context, WXUtils.APPID);
        if (!msgApi.isWXAppInstalled()) {
            ToastUtils.showShort("您还没有安装微信");
            return;
        }
        //网页链接配置
        final WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = webUrl;
        //消息内容配置
        final WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = title;
        msg.description = description;
        //请求配置
        final SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = String.valueOf(System.currentTimeMillis());
        req.scene = scene;
        //缩略图配置
        if (!TextUtils.isEmpty(imageUrl)) {
            RequestOptions myOptions = new RequestOptions()
                    .override(40, 40);
            Glide.with(context).load(imageUrl).apply(myOptions).into(new SimpleTarget<Drawable>() {
                @Override
                public void onResourceReady(@NonNull Drawable drawable, @Nullable Transition<? super Drawable> transition) {
                    BitmapDrawable temp = (BitmapDrawable) drawable;
                    Bitmap thumb = temp.getBitmap();
                    msg.thumbData = bmpToByteArray(thumb, false);
                    req.message = msg;
                    msgApi.sendReq(req);
                }

                @Override
                public void onLoadFailed(@Nullable Drawable errorDrawable) {
                    Bitmap thumb = BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher);
                    req.message = msg;
                    msg.thumbData = bmpToByteArray(thumb, false);
                    msgApi.sendReq(req);
                }
            });
        } else {
            Bitmap thumb = BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher);
            req.message = msg;
            msg.thumbData = bmpToByteArray(thumb, false);
            msgApi.sendReq(req);
        }
    }

    /**
     * Bitmap转btye64
     */
    public static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, output);
        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (needRecycle) {
            bmp.recycle();
        }
        return result;
    }

}
